package com.ljw.community.service.impl;

import com.ljw.community.entity.Admin;
import com.ljw.community.entity.Tag;
import com.ljw.community.mapper.AdminMapper;
import com.ljw.community.mapper.CommonMapper;
import com.ljw.community.mapper.TagMapper;
import com.ljw.community.mapper.TopicMapper;
import com.ljw.community.service.TagService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;
    @Resource
    private TopicMapper topicMapper;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private AdminMapper adminMapper;

    @Override
    public List<Tag> loadTagList(int curr, int limit) {
        int startIndex = curr * limit - limit;
        List<Tag> list = tagMapper.loadTagList(startIndex, limit);
        //查出每个板块的话题数和创建人
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                Tag tag = list.get(i);
                int topicCount = topicMapper.countByTagId(tag.getId());   //获取话题数
                String creatorLoginName = commonMapper.getLoginNameById(tag.getCreatorId());  //获取创建人
                tag.setCreatorLoginName(creatorLoginName);
                tag.setTopicCount(topicCount);
                list.set(i, tag);
            }
        }
        return list;
    }

    @Override
    public int manageTag(Tag tag, String opera, String loginName) {
        Admin admin = adminMapper.getByLoginName(loginName);
        if (admin == null) {
            return -1;
        }
        tag.setCreatorId(admin.getId());
        //根据opera执行不同操作
        if ("new".equals(opera)) {
            //判断同名
            List<Tag> list = tagMapper.loadTagList(0, 9999);
            if (list != null && !list.isEmpty())
                for (Tag dbTag : list) {
                    if (tag.getTagName().equals(dbTag.getTagName())) {
                        return 0;
                    }
                }
            //执行插入
            tag.setId(UUID.randomUUID().toString().replace("-", ""));
            tag.setCreateTime(new Date());
            return tagMapper.insert(tag);
        } else if ("delete".equals(opera)) {
            return tagMapper.updateById(tag);
        }
        return -1;
    }
}
